package homework.score.system;

import homework.score.util.InputUtil;

import java.util.Stack;

public class ManagementSystem {

    private INode root;
    private INode current;
    private Stack<INode> location = new Stack<INode>();

    public ManagementSystem(INode root) {
        this.root = root;
        current = root;
        location.push(root);
    }

    public INode enter(int i) {
        INode node = current.getNode(i);

        if (node instanceof CommandNode) {
            try {
                node.execute();
            } catch (Exception e) {
                String msg = "[!] " + e.getClass().getSimpleName() + ": " + e.getMessage();
                System.out.println(msg);
            }
        } else {
            current = node;
            location.push(current);
        }

        return current;
    }

    public INode exit() {
        if (location.size() > 1) {
            location.pop();
            current = location.peek();
        }

        return current;
    }

    public void listItems() {
        System.out.printf("\n===================== %s =====================\n\n\t", current.getName());
        System.out.println(current.getDescription());
        System.out.println();

        printLocation();
        System.out.println();
        if (location.size() > 1) {
            System.out.println("0. 返回");
        }

        for (int i=0;i<current.size();i++) {
            INode node = current.getNode(i);

            System.out.print(i+1+". ");
            System.out.println(node.getName());
        }
        System.out.println();
    }

    public int getInputNumber() {
        int i = -1;
        while (i == -1) {
            i = InputUtil.input(Integer.class, "\n[-] 请输入序号: ", "[!] 非法输入");

            if (i < 0 || i > current.size() || (i == 0 && current == root)) {
                i = -1;
                System.out.println("[!] 没有此项");
            }
        }

        return i;
    }

    public void printLocation() {
        StringBuilder builder = new StringBuilder("[*] 位置: ");
        for (INode node : location) {
            builder.append(node.getName());

            if (node != current) {
                builder.append(" > ");
            }
        }

        System.out.println(builder.toString());
    }

    public void run() {
        while (location.size() > 0) {

            listItems();

            int n = getInputNumber();

            if (n == 0) {
                exit();
            } else {
                enter(n-1);
            }
        }
    }
}
